<script lang="ts" setup>
import { ref } from 'vue'
import { useVbenForm } from '#/adapter/form'
import { useVbenModal } from '@vben/common-ui'
import { Button, message } from 'ant-design-vue'
import { createDownloadRecord, updateDownloadRecord, getDownloadRecordInfo } from '#/api/downloadRecord'
import dayjs from 'dayjs'

interface RowType {
  id?: number
  title?: string
  total_num?: number
  total_page?: number
  current_page?: number
  progress?: number
  down_status?: number
  start_time?: string
  end_time?: string
  created_at?: string
  admin_id?: number
  file_url?: string
  down_body?: string
  down_name?: string
  error_msg?: string
  down_type?: string
  access_mode?: string
  time_range?: string
  file_name?: string
  user_id?: number
  company_id?: number
  [key: string]: any
}

const emit = defineEmits(['fetchData'])

const recordId = ref(0)

// 表单配置
const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  showDefaultActions: false,
  layout: 'horizontal',
  schema: [
    {
      component: 'InputNumber',
      fieldName: 'user_id',
      label: 'downloadRecord.user_id',
      componentProps: {
        placeholder: '请输入用户ID',
      },
    },
    {
      component: 'InputNumber',
      fieldName: 'company_id',
      label: 'downloadRecord.company_id',
      componentProps: {
        placeholder: '请输入公司ID',
      },
    },
    {
      component: 'Input',
      fieldName: 'title',
      label: 'downloadRecord.title',
      componentProps: {
        placeholder: '请输入标题',
        allowClear: true,
      },
    },
    {
      component: 'InputNumber',
      fieldName: 'total_num',
      label: 'downloadRecord.total_num',
      componentProps: {
        min: 0,
        placeholder: '请输入总数量',
      },
    },
    {
      component: 'InputNumber',
      fieldName: 'total_page',
      label: 'downloadRecord.total_page',
      componentProps: {
        min: 0,
        placeholder: '请输入总页数',
      },
    },
    {
      component: 'InputNumber',
      fieldName: 'current_page',
      label: 'downloadRecord.current_page',
      componentProps: {
        min: 0,
        placeholder: '请输入当前页',
      },
    },
    {
      component: 'InputNumber',
      fieldName: 'progress',
      label: 'downloadRecord.progress',
      componentProps: {
        min: 0,
        max: 100,
        placeholder: '请输入进度(0-100)',
      },
    },
    {
      component: 'Input',
      fieldName: 'access_mode',
      label: 'downloadRecord.access_mode',
      componentProps: {
        placeholder: '请输入访问模式',
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'down_type',
      label: 'downloadRecord.down_type',
      componentProps: {
        placeholder: '请输入下载类型',
        allowClear: true,
      },
    },
    {
      component: 'Textarea',
      fieldName: 'down_body',
      label: 'downloadRecord.down_body',
      formItemClass: 'col-span-2',
      componentProps: {
        placeholder: '请输入下载内容',
        rows: 3,
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'down_name',
      label: 'downloadRecord.down_name',
      componentProps: {
        placeholder: '请输入下载名称',
        allowClear: true,
      },
    },
    {
      component: 'Textarea',
      fieldName: 'error_msg',
      label: 'downloadRecord.error_msg',
      formItemClass: 'col-span-2',
      componentProps: {
        placeholder: '请输入错误信息',
        rows: 3,
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'time_range',
      label: 'downloadRecord.time_range',
      componentProps: {
        placeholder: '请输入时间范围',
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'file_name',
      label: 'downloadRecord.file_name',
      componentProps: {
        placeholder: '请输入文件名称',
        allowClear: true,
      },
    },
    {
      component: 'Textarea',
      fieldName: 'file_url',
      label: 'downloadRecord.file_url',
      formItemClass: 'col-span-2',
      componentProps: {
        placeholder: '请输入文件路径',
        rows: 3,
        allowClear: true,
      },
    },
    {
      component: 'InputNumber',
      fieldName: 'down_status',
      label: 'downloadRecord.down_status',
      componentProps: {
        min: 0,
        placeholder: '请输入状态(0:待完成,1:已完成,3:停止下载,9:错误)',
      },
    },
    {
      component: 'DatePicker',
      fieldName: 'start_time',
      label: 'downloadRecord.start_time',
      componentProps: {
        showTime: true,
        format: 'YYYY-MM-DD HH:mm:ss',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        placeholder: '请选择开始时间',
      },
    },
    {
      component: 'DatePicker',
      fieldName: 'end_time',
      label: 'downloadRecord.end_time',
      componentProps: {
        showTime: true,
        format: 'YYYY-MM-DD HH:mm:ss',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        placeholder: '请选择结束时间',
      },
    },
    {
      component: 'DatePicker',
      fieldName: 'created_at',
      label: 'downloadRecord.created_at',
      componentProps: {
        showTime: true,
        format: 'YYYY-MM-DD HH:mm:ss',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        placeholder: '请选择创建时间',
      },
    },
  ],
  wrapperClass: 'grid grid-cols-2 gap-4',
})

// 提交表单
const onSubmit = async () => {
  const { valid } = await formApi.validate()
  if (valid) {
    modalApi.lock()
    try {
      const formValues = await formApi.getValues()

      // 格式化日期字段
      if (formValues.start_time) {
        formValues.start_time = dayjs(formValues.start_time).format('YYYY-MM-DD HH:mm:ss')
      }
      if (formValues.end_time) {
        formValues.end_time = dayjs(formValues.end_time).format('YYYY-MM-DD HH:mm:ss')
      }
      if (formValues.created_at) {
        formValues.created_at = dayjs(formValues.created_at).format('YYYY-MM-DD HH:mm:ss')
      }

      if (recordId.value) {
        await updateDownloadRecord({ ...formValues, id: recordId.value })
        message.success('编辑成功')
      } else {
        await createDownloadRecord(formValues)
        message.success('添加成功')
      }
      emit('fetchData')
      modalApi.close()
    } finally {
      modalApi.lock(false)
    }
  }
}

// 获取详情数据
const fetchData = async () => {
  if (recordId.value) {
    try {
      const res = await getDownloadRecordInfo({ id: recordId.value })
      formApi.setValues(res.row)
    } catch (error) {
      message.error('获取详情失败')
    }
  }
}

// 初始化清除
const initClear = () => {
  recordId.value = 0
  formApi.resetForm()
}

const [Modal, modalApi] = useVbenModal({
  class: 'w-3/5',
  appendToMain: true,
  showConfirmButton: false,
  showCancelButton: false,
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const routerData = modalApi.getData<Record<string, any>>()
      initClear()
      if (routerData.info?.id) {
        recordId.value = routerData.info.id
        fetchData()
      }
    }
  },
})
</script>

<template>
  <Modal :title="recordId ? '编辑下载记录' : '新增下载记录'">
    <div class="p-4 max-h-[70vh] overflow-y-auto">
      <Form />
    </div>

    <template #footer>
      <div class="flex justify-end space-x-2">
        <Button @click="modalApi.close()">取消</Button>
        <Button type="primary" @click="onSubmit()">保存</Button>
      </div>
    </template>
  </Modal>
</template>
